package cn.dmrliu.edu.realtime.app.func;

;
import cn.dmrliu.edu.realtime.util.DimUtil;
import cn.dmrliu.edu.realtime.util.ThreadPoolUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.async.ResultFuture;
import org.apache.flink.streaming.api.functions.async.RichAsyncFunction;

import java.util.Collections;
import java.util.concurrent.ExecutorService;

public abstract class DimAsyncFunction<T> extends RichAsyncFunction<T, T> {
    // 获取一个线程
    private ExecutorService executor;
    private String tableName;

    public DimAsyncFunction(String tableName) {
        this.tableName = tableName;
    }

    @Override
    public void open(Configuration parameters) throws Exception {
        executor = ThreadPoolUtil.getInstance();

    }

    @Override
    public void asyncInvoke(T input, ResultFuture<T> resultFuture) throws Exception {
        executor.submit(new Runnable() {
            @Override
            public void run() {
                String key = getKey(input);
                JSONObject dimInfo = DimUtil.getDimInfo(tableName, key);
                if (dimInfo != null) {
                    join(input, dimInfo);
                }
                resultFuture.complete(Collections.singleton(input));

            }
        });
    }

    // 从t对象中获取key
    public abstract String getKey(T t);

    // 关联操作
    public abstract void join(T t, JSONObject dimInfo);

}